package sporteam.web.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import org.json.JSONException;
import org.json.JSONObject;


 
public class JsonUtils
{
	  private static final Logger MyLog = Logger.getLogger(JsonUtils.class.getName());
	  
	  // parse all data(byte wise) from rd 
	  private static String readAll(Reader rd) throws IOException 
	  {
	    StringBuilder sb = new StringBuilder();
	    int cp;
	    
	    //read bytes
	    while ((cp = rd.read()) != -1)
	    {
	      // build string
	      sb.append((char) cp);
	    }
	    return sb.toString();
	  }

	  
	  // given a URL, read a and return the JsonObject posted to it(given that it was 
	  // properly posted
	  public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException
	  {
	    InputStream is = new URL(url).openStream();
	    try 
	    {
	      BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
	      String jsonText = readAll(rd);
	      JSONObject json = new JSONObject(jsonText);
	      return json;
	    }
	    catch(Exception e)
	    {
	    	 
	    }
	    finally 
	    {
	      is.close();
	    }
	    
	    return null;
	  }

	  //retrieve json object from client HTTP request
	  public static JSONObject RetrieveJsonFromRequest(HttpServletRequest request)
	  {
		String data;
		JSONObject json = null;
		
		try
		{
		  // get request information in buffered reader
		  BufferedReader reader = request.getReader();
	      StringBuilder sb = new StringBuilder();
	      String line = reader.readLine();
	      
	      //build request string representation
	       while (line != null)
	       {
	           sb.append(line + "\n");
	           line = reader.readLine();
	       }
	       
	       //close reader
	       reader.close();
	       
	       //get final data
	       data = sb.toString();
	       
	       //build new json object from data
		   json = new JSONObject(data);
	    }
		catch(Exception e)
		{
			MyLog.warning(e.toString());
		}
		
		 return json;
		
		
	  }
	   
	
}
